<template>
  <div>
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :span="4">
          <p>状态</p>
          <el-select v-model="IsEnabled" size="mini" @change="getStudent()">
            <el-option value="" label="全部" />
            <el-option :value="true" label="启用" />
            <el-option :value="false" label="停用" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <p>班级</p>
          <el-select v-model="Api_GET_ClubStudentQO.ClassId" size="mini" placeholder="请选择班级" clearable @change="getStudent()">
            <el-option value="" label="全部" />
            <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <p>姓名</p>
          <el-input v-model="Api_GET_ClubStudentQO.StudentName" placeholder="请输入姓名" size="mini" clearable @change="getStudent()" />
        </el-col>
        <el-col :span="4">
          <p>证件号</p>
          <el-input v-model="Api_GET_ClubStudentQO.IdCardNumber" placeholder="请输入证件号" size="mini" clearable @change="getStudent()" />
        </el-col>
        <el-col :span="2.5">
          <el-button type="primary" style="margin-top:25px" size="mini" @click="checkst">筛选</el-button>
        </el-col>
      </el-row>
    </div>
    <div style="margin-top:12px">
      <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="add">添加学员</el-button>
      <el-button icon="el-icon-download" size="mini"><a :href="dowfile" download="学员模板.xlsx">下载导入模板</a></el-button>
      <div style="display:inline-block;width:80px;height:28px;margin-right:10px;margin-left:10px;">
        <el-upload
          class="upload_file"
          :action="importAction"
          :before-upload="beforeUpload"
          :http-request="upLoadFile"
          :auto-upload="true"
          :show-file-list="false"
          accept=".xlsx, .xls"
        >
          <el-button :loading="btnUpLoading" type="success" size="mini">导入学员</el-button>
        </el-upload>
      </div>
      <el-button type="warning" icon="el-icon-download" size="mini" :loading="btnDownLoading" @click="exportstudent()">导出学员列表</el-button>
    </div>
    <div style="margin-top:20px">
      <el-table v-loading="tableLoading" class="gl_table_noBorder" size="mini" :data="tableData">
        <el-table-column type="index" label="序号" align="center" width="100" />
        <el-table-column label="姓名" align="center" width="70">
          <template slot-scope="{row}">
            <PersonalImage :imgurl="row.imagePath" imgheight="60px" />
          </template>
        </el-table-column>
        <el-table-column prop="name" />
        <el-table-column label="证件号码" prop="idCardNumber" />
        <el-table-column label="有效课时" align="center">
          <template slot-scope="{row}">
            <p>{{ row.classPeriod }}</p>
          </template>
        </el-table-column>
        <el-table-column label="最长有效期">
          <template slot-scope="{row}">
            <span v-if="row.effectiveDate">
              {{ row.effectiveDate | FormatDate('yyyy-MM-dd') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="所在班级">
          <template slot-scope="{row}">
            <div v-for="(classs,index) in row.classStudents" :key="index">
              {{ classs.class.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="教练">
          <template slot-scope="{row}">
            <div v-for="coach in row.studentCoachs" :key="coach.id">
              {{ coach.employee && coach.employee.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="{row}">
            <div v-if="row.isEnable === true"><i class="success_circle" />已启用</div>
            <div v-else><i class="error_circle" />已停用</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button v-if="row.isEnable === true" type="text" size="mini" style="color:red" @click="stop(row)">停用</el-button>
            <el-button v-if="row.isEnable === false" type="text" size="mini" @click="start(row)">启用</el-button>
            <el-button type="text" size="mini" style="color:#1990FF" @click="editStudent(row)">编辑</el-button>
            <el-button type="text" size="mini" style="color:#FF3434" @click="deleteStudent(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <add-student ref="addStudent" @flag="go" @addStudent="addStudent" />
    <el-row class="gl_pt_15" style="text-align: right;">
      <el-pagination
        :current-page="Api_GET_ClubStudentQO.Page"
        :page-size="Api_GET_ClubStudentQO.MaxResultCount"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="sizeChange"
        @current-change="pageIndexChange"
      />
    </el-row>
  </div>
</template>
<script>
import PersonalImage from '@/components/PersonalImage/index';
import { api_GET_DownLoadFileAddHeader, api_Post_UploadFileAddHeader } from '@/extend/api/file';
import { errorText } from '@/lib';
import { api_GET_ClubStudent, api_PUT_ClubStudentStudentStausStudentId, api_DELETE_ClubStudentStudentStudentId, api_GET_ClubClass } from '@/extend/api/hallswaggerApi/app.js';
import { Api_GET_ClubStudentQO, Api_PUT_ClubStudentStudentStausStudentIdQO } from '@/lib/form/hall/swaggerForm';
import { mapState, mapActions } from 'vuex';
import addStudent from '../addStudent.vue';
export default {
  components: {
    addStudent,
    PersonalImage
  },
  data() {
    return {
      btnDownLoading: false,
      btnUpLoading: false,
      tableLoading: false,
      file: '',
      dowfile: `${WEB_CONFIG.VUE_APP_TEMPLATE_STATIC_FILE_RUL}/static/import_students_template.xlsx`,
      importAction: `${WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE}/api/app/club/importStudent`,
      currentPage: 1,
      IsEnabled: '',
      totalPage: 0,
      importLoading: false,
      tableData: [],
      father: {},
      Api_GET_ClubStudentQO: new Api_GET_ClubStudentQO(), // 学员列表
      Api_PUT_ClubStudentStudentStausStudentIdQO: new Api_PUT_ClubStudentStudentStausStudentIdQO(), // 学员停用,
      GetStudentInput: {},
      classList: []
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict,
      cache: state => state.dict.cache,
      user: state => state.user.currentOU
    })
  },
  created() {
    console.log(this.dict);
    this.getClass();
    if (this.$route.query.classId && this.$route.query.classId === 'empty') {
      this.Api_GET_ClubStudentQO.ClassId = '00000000-0000-0000-0000-000000000000';
    } else {
      this.Api_GET_ClubStudentQO.ClassId = '';
    }
    this.getStudent();
    this.getDict();
    this.checkQueryHasAdd();
  },
  methods: {
    beforeUpload(file) {
      this.file = file;
    },
    // 导入名单
    upLoadFile() {
      var _this = this;
      _this.btnUpLoading = true;
      console.log(this.user);
      api_Post_UploadFileAddHeader(this.importAction, this.file, { CURRENT_OU: this.user }).then(res => {
        _this.$message({
          type: 'success',
          duration: 10000,
          showClose: true,
          message: `导入成功`
        });
        _this.getStudent(this.Api_GET_ClubStudentQO.Page);
        _this.btnUpLoading = false;
      },
      rej => {
        _this.btnUpLoading = false;
        const err = JSON.parse(rej.request.response).error.message;
        console.dir(err);
        _this.$message({
          type: 'error',
          message: '导入失败 ' + err
        });
      }
      ).catch(error => {
        console.log(error);
        _this.btnUpLoading = false;
        _this.$message({
          type: 'error',
          message: '导入失败 '
        });
      });
    },
    ...mapActions({ getDict: 'dict/getDict' }),
    checkQueryHasAdd () {
      const query = this.$route.query;
      if (query.add === 'true') {
        this.add();
      }
    },
    add() {
      this.$nextTick(() => {
        this.$refs.addStudent.dialogVisible = true;
      });
    },
    // 上传文件限制
    check(file) {
      const isJPG =
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel';
      if (!isJPG) {
        this.$message.error('上传文件只能是 .xls或者.xlsx 格式!');
      }
      return isJPG;
    },
    // 上传图片的api
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.$store.state.user.token
        }
      };
      return axios.post(url, file, config);
    },
    // 控制添加页面
    go(a) {
    },
    addStudent(student) {
      this.father = student;
    },
    // 获取班级列表
    getClass() {
      var that = this;
      api_GET_ClubClass({ HasStudent: true }).then(res => {
        that.classList = res.items || [];
        that.classList.unshift({ id: '00000000-0000-0000-0000-000000000000', name: '待分配' });
        if (this.$route.query.classId && this.$route.query.classId === 'empty') {
          this.Api_GET_ClubStudentQO.ClassId = '00000000-0000-0000-0000-000000000000';
        }
      }).catch(error => {
        that.$message({ type: 'error', message: error.error.message || '获取班级列表失败' });
      });
    },
    // 获取学生列表
    getStudent(Page) {
      this.tableLoading = true;
      // this.Api_GET_ClubStudentQO.IncludeStudentContacts = true;
      this.Api_GET_ClubStudentQO.IncludeStudentCoachs = true;
      this.Api_GET_ClubStudentQO.IncludeClassStudents = true;
      // this.Api_GET_ClubStudentQO.IncludeGender = true;
      // this.Api_GET_ClubStudentQO.IncludeIdCardType = true;
      this.Api_GET_ClubStudentQO.IncludeStudentMembershipCards = true;
      this.Api_GET_ClubStudentQO.IsEnable = this.IsEnabled;
      this.Api_GET_ClubStudentQO.Sorting = 'creationTime DESC';
      this.Api_GET_ClubStudentQO.Page = Page || 1;
      this.Api_GET_ClubStudentQO.SkipCount = (this.Api_GET_ClubStudentQO.Page - 1) * this.Api_GET_ClubStudentQO.MaxResultCount;
      api_GET_ClubStudent(this.Api_GET_ClubStudentQO).then((res) => {
        console.log(res);
        this.totalPage = res.totalCount;
        this.tableData = res.items;
        this.tableLoading = false;
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 分页
    sizeChange(MaxResultCount) {
      this.Api_GET_ClubStudentQO.MaxResultCount = MaxResultCount;
      this.getStudent();
    },
    pageIndexChange(currentPage) {
      this.getStudent(currentPage);
    },
    // 停用/启用
    stop(row) {
      this.tableLoading = true;
      this.Api_PUT_ClubStudentStudentStausStudentIdQO.isEnable = false;
      api_PUT_ClubStudentStudentStausStudentId(row.id, this.Api_PUT_ClubStudentStudentStausStudentIdQO).then((res) => {
        this.$message({
          message: '停用成功',
          type: 'success'
        });
        this.tableLoading = false;
        this.getStudent(this.Api_GET_ClubStudentQO.Page);
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    start(row) {
      this.tableLoading = true;
      this.Api_PUT_ClubStudentStudentStausStudentIdQO.isEnable = true;
      api_PUT_ClubStudentStudentStausStudentId(row.id, this.Api_PUT_ClubStudentStudentStausStudentIdQO).then((res) => {
        this.$message({
          message: '启用成功',
          type: 'success'
        });
        this.tableLoading = false;
        this.getStudent(this.Api_GET_ClubStudentQO.Page);
      }, error => {
        this.tableLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 编辑学员
    editStudent(row) {
      this.$router.push({ 'name': 'StudentType', query: { 'rid': row.registerId, 'id': row.id, 'ed': 'U', sname: 'membership' }});
    },
    // 删除学员
    deleteStudent(row) {
      this.$confirm(`您确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_ClubStudentStudentStudentId(row.id).then(res => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getStudent(this.Api_GET_ClubStudentQO.Page);
          }, error => {
            const _msg = error.error.message || error.message;
            this.$message({ type: 'error', message: _msg });
          });
        });
    },
    checkst() {
      this.getStudent();
    },
    exportstudent() {
      this.GetStudentInput.IsEnable = this.Api_GET_ClubStudentQO.IsEnable;
      this.GetStudentInput.PhoneNumber = this.Api_GET_ClubStudentQO.PhoneNumber;
      this.GetStudentInput.ClassId = '';
      this.GetStudentInput.StudentName = this.Api_GET_ClubStudentQO.StudentName;
      this.GetStudentInput.IncludeStudentContacts = true;
      this.GetStudentInput.IncludeGender = true;
      this.GetStudentInput.IncludeIdCardType = true;
      this.GetStudentInput.IncludeStudentMembershipCards = true;
      this.GetStudentInput.IncludeStudentCoachs = true;
      this.GetStudentInput.IncludeClassStudents = true;
      this.GetStudentInput = JSON.stringify(this.GetStudentInput);
      var that = this;
      const tempUrl = `/api/excel`;
      const fileName = '学员' + '.xlsx';
      this.btnDownLoading = true;
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: 'StudentExcel', GetStudentInput: this.GetStudentInput }, WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE).then(res => {
        that.btnDownLoading = false;
        this.GetStudentInput = {};
      }).catch(error => {
        this.GetStudentInput = {};
        that.btnDownLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    exportdown() {
      this.GetStudentInput.IsEnable = true;
      this.GetStudentInput.ClassId = '';
      this.GetStudentInput.IncludeStudentContacts = true;
      this.GetStudentInput.IncludeGender = true;
      this.GetStudentInput.IncludeIdCardType = true;
      this.GetStudentInput.IncludeStudentMembershipCards = true;
      this.GetStudentInput.IncludeStudentCoachs = true;
      this.GetStudentInput.IncludeClassStudents = true;
      this.GetStudentInput = JSON.stringify(this.GetStudentInput);
      var that = this;
      that.downloadLoading = true;
      const tempUrl = `/api/excel`;
      const fileName = '学员' + '.xlsx';
      api_GET_DownLoadFileAddHeader(tempUrl, fileName, { reportName: 'StudentExcel', GetStudentInput: this.GetStudentInput }, WEB_CONFIG.VUE_APP_SWAGGER_HALL_BASE).then(res => {
        that.downloadLoading = false;
        this.GetStudentInput = {};
      }).catch(error => {
        this.GetStudentInput = {};
        that.downloadLoading = false;
        errorText(error).then(function(text) {
          that.$message({ type: 'error', message: text });
        });
      });
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    }
    // downfile() {
    //   href="/static/import_students_template.xlsx";
    //   const tempUrl = `.xlsx`;
    //   const fileName = '学员' + '.xlsx';
    //   api_GET_DownLoadFileAddHeader(tempUrl, fileName, { }, '/static/import_students_template').then(res => {});
    // }
  }
};
</script>

<style scoped>
  .roodsPhoto{
    width: 60px;
    height: 60px;
    vertical-align: middle;
  }
.success_circle {
  display: inline-block;
  margin-right: 8px;
  width: 6px;
  height: 6px;
  background: #14CE67;
  border-radius: 50%;
}
.error_circle {
  display: inline-block;
  margin-right: 8px;
  width: 6px;
  height: 6px;
  background: #FF3434;
  border-radius: 50%;
}
</style>
